package com.hsxc.cdz.mgmt.security;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.hsxc.cdz.base.bean.ConsoleUser;
import com.hsxc.cdz.base.bean.MyUser;
import com.hsxc.cdz.mgmt.user.MyUserManager;
import com.hsxc.cdz.mgmt.user.UserManager;

/**
 * @author wpfei
 *         授权
 */

@Component
public class SystemAuthorizingRealm extends AuthorizingRealm {
    protected static Logger log = Logger.getLogger("SystemAuthorizingRealm");

    //	  // 认证
    //    super.setAuthenticationCachingEnabled(false);
    //    // 授权
    //    super.setAuthorizationCacheName(AUTHCACHENAME);
    //===================================================================================================
    private final static int userState = 0;

    @Resource(name = "userManager")
    private UserManager userManager;

    public void setUserService(UserManager userManager) {
        this.userManager = userManager;
    }

    //注入myUserManger类
    @Resource(name = "myUserManager")
    private MyUserManager myUserManager;

    public void setAppUserService(MyUserManager myUserManager) {
        this.myUserManager = myUserManager;
    }

    //=========================================================================================================
    private int userType;

    //判断用户类型
    protected int getUserType() {
        int myUserType = myUserManager.getUSERTYPE();//0
        int conUserType = userManager.getUSERTYPE();//0
        if (myUserType != 0) {
            log.debug("============================" + "当前用户类型" + conUserType + "==============================");
            userType = myUserType;
            myUserManager.setUSERTYPE(userState);
            log.debug("=================================用户类型" + userType + "===========================");

        }

        if (conUserType != 0) {
            log.debug("============================" + "当前用户类型" + conUserType + "===============================");
            userType = conUserType;
            userManager.setUSERTYPE(userState);
            log.debug("=================================用户类型" + userType + "===========================");

        }

        return userType;

    }

    //=============================================================================================================
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.debug("----------------------------授权开始--------------------------------------------");
        log.debug("principals的值是：" + principals);
        String userName = (String) principals.fromRealm(getName()).iterator().next();
        log.debug(userName);
        //根据用户名查找拥有的角色
        log.debug("------------------------------------------获取角色----------------------------------");
        List<String> roles = userManager.getUserRoles(userName);
        if (roles != null) {
            log.debug("--------------------------------------正式授权----------------------------------");
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //roles.stream();
            for (String role : roles) {
                info.addRole(role);
            }
            return info;
        } else {
            return null;
        }


    }

    //===============================================================================================================
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        AuthenticationInfo authcInfo;
        ConsoleUser consoleUser = null;
        MyUser myUser = null;
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        log.debug("验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
        log.debug("-------------------------------" + "用户认证..." + "------------------------------------------------------");

        if (getUserType() == 1) {
            consoleUser = userManager.loadConUserByName(token.getUsername());
        }
        if (getUserType() == 2) {
            myUser = myUserManager.loadMyUserByMobile(token.getUsername());
        }
        log.debug("---------------------------------" + myUser + "-------------------------------------");
        log.debug("---------------------------------" + token.getUsername() + "-----------------------------");

        if (consoleUser != null) {
            log.debug("运行到步骤conuser");
            log.debug("数据库中的" + consoleUser.getPassword());
            log.debug("登录输入" + token.getPassword());
            authcInfo = new SimpleAuthenticationInfo(consoleUser.getUser_name().toString().trim(), consoleUser.getPassword().toString().trim(), getName());
            return authcInfo;
        }
        if (myUser != null) {
            log.debug("运行到步骤myuser");
            log.debug("数据库中的" + myUser.getPassword());
            log.debug("数据库电话" + myUser.getTel());
            String tel = myUser.getTel().toString().trim();
            String password = myUser.getPassword().toString().trim();
            authcInfo = new SimpleAuthenticationInfo(tel, password, getName());

            log.debug("验证返回结果为" + authcInfo);
            return authcInfo;
        }
        return null;
    }

    //==================================================================================================================
    @Override
    public String getName() {
        return getClass().getName();
    }
}
